#include "cmdline.h"

const char* c_UsageText[] = {
"Usage: cuTracer -s<scene> -w<width> -h<height> -d<traceDepth> -o<output> [-t<num_threads>] [-gui]",
"",
"",
"Example:        cuTracer -sscene1.xml -w800 -h600 -d6 -oout.tga -t2 -gui"
};



void CommandLine::PrintUsage(void)
{
	const int numLines = sizeof(c_UsageText) / sizeof(c_UsageText[0]);
	for (int i = 0; i < numLines; ++i)
		std::cout << c_UsageText[i] << std::endl;
}


CommandLine::CommandLine()
{
}

CommandLine::~CommandLine()
{
}

int CommandLine::ParseArgv(int argc, char** argv)
{
	m_Parameters.clear();
	for (int i = 0; i < argc; ++i)
	{
		int paramType = this->FindParameter(argv[i]);
		if (paramType == NUM_CMD_PARAMS)
		{
			std::cout << "Unknown parameter found: " << argv[i] << std::endl;
			return 0;
		}
		else if (!this->CheckParameter(argv[i], paramType))
		{
			std::cout << "Incorrect data for parameter " << s_KnownCommandLineParameters[paramType].name << std::endl;
			return 0;
		}

		const SCommandLineParameterTemplate& param = s_KnownCommandLineParameters[paramType];
		m_Parameters.push_back(TCmdParametersVec::value_type(paramType, argv[i] + param.nameLen));
	}

	return static_cast<int>(m_Parameters.size());
}

int CommandLine::GetParameterIdx(int paramType) const
{
	for (TCmdParametersVec::size_type i = 0; i < m_Parameters.size(); ++i)
		if (m_Parameters[i].first == paramType)
			return static_cast<int>(i);

	return -1;
}

int CommandLine::GetParameterType(int idx) const
{
	return m_Parameters[idx].first;
}

const std::string& CommandLine::GetParameterData(int idx) const
{
	return m_Parameters[idx].second;
}


int CommandLine::FindParameter(const char* arg) const
{
	for (int i = 0; i < k_NumCommandLineParameters; ++i)
	{
		if (strncmp(arg, s_KnownCommandLineParameters[i].name, s_KnownCommandLineParameters[i].nameLen) == 0)
			return i;
	}

	return NUM_CMD_PARAMS;
}

bool CommandLine::CheckParameter(const char* paramArg, int paramType) const
{
	const SCommandLineParameterTemplate& param = s_KnownCommandLineParameters[paramType];

	// iOrange - check without data
	if (!param.needData && (strlen(paramArg) != param.nameLen))
		return false;

	// iOrange - check with data
	if (param.needData && (strlen(paramArg) < (param.nameLen + 1)))
		return false;

	return true;
}
